//
//  GoodsListCell.m
//  夺宝吧
//
//  Created by xiaocai on 15/6/15.
//  Copyright (c) 2015年 FangYuan. All rights reserved.
//

#import "GoodsListCell.h"
#import "LockView.h"
#import "NSString+GetSize.h"
#import "ShoppingCarVC.h"

@interface GoodsListCell ()
{
    __weak IBOutlet UIImageView *pdcImg;
    __weak IBOutlet UILabel *titleLab;
    __weak IBOutlet UILabel *allLab;
    __weak IBOutlet UILabel *leftLab;
    __weak IBOutlet UILabel *nowLab;
    UIProgressView *progressView;
    __weak IBOutlet UIButton *collecBtn;
    //记录当前的数据模型
    ProductModel *_currentModel;
    //动画层
    CALayer *ani_layer;
    
    __weak IBOutlet UIButton *is_locked;
}
@end
@implementation GoodsListCell

- (void)awakeFromNib {
    // Initialization code
    //改变进度条的默认高度
    progressView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
    // progressView's frame will be small/standard height
    AppDelegate *app = [UIApplication sharedApplication].delegate;
    progressView.frame = CGRectMake(CGRectGetMinX(allLab.frame), CGRectGetMidY(collecBtn.frame), 176*app.autoSizeScaleX, 2);
    progressView.progressTintColor = [UIColor redColor];
    progressView.layer.masksToBounds = YES;
    progressView.layer.cornerRadius = 2;
    
    //改变进度条的默认高度
    CGAffineTransform transform = CGAffineTransformMakeScale(1.0f, 2.8f);
    progressView.transform = transform;
    [self addSubview:progressView];
    
    [self addSubview:[WYPublic getFenGexian:0 :self.frame.size.height - 1 :WYMWITH :0.5]];
    
    NSString *show_shopping = [[NSUserDefaults standardUserDefaults] valueForKey:@"show_shopping"];
    [collecBtn setHidden:YES];
    if (show_shopping.integerValue == 1) {
        [collecBtn setHidden:NO];
    }

}
//填充数据的方法
- (void)fillCellWithModel:(ProductModel *)model
{
    _currentModel = model;
    [pdcImg sd_setImageWithURL:[NSURL URLWithString:model.pdc_img_path] placeholderImage:[UIImage imageNamed:@"moren"]];
    titleLab.text = [NSString stringWithFormat:@"(第%@期)%@",model.pdc_qishu,model.pdc_title];
    allLab.text = [NSString stringWithFormat:@"%@%@次",@"总需:",model.pdc_people_indeed];
    nowLab.text = [NSString stringWithFormat:@"%@%@次",@"已购买:",model.pdc_people_now];
    leftLab.attributedText = [WYPublic getRedMiddleStrWithLeft:@"剩余:" Middle:model.pdc_people_left RightStr:@"次" Font:12];
    progressView.progress = ([model.pdc_people_now intValue]*1.0/[model.pdc_people_indeed intValue]);
    if (_currentModel.is_locked.integerValue == 1) {
        [is_locked setHidden:NO];
        [progressView setProgressTintColor:[UIColor colorWithRed:238/255.0 green:170/255.0 blue:0/2555.0 alpha:1.0]];
    }else{
        [progressView setProgressTintColor:[UIColor redColor]];
        [is_locked setHidden:YES];
    }

}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

- (IBAction)lockTapped:(UIButton *)sender
{
    [WYPublic addHudToWindow];
    NSDictionary *params = @{@"id":_currentModel.pdc_id};
    [WYRequest startPostForDicWithUrlStR:[NSString stringWithFormat:@"%@%@",DBB_IP,@"api/ApiGoods/getLockedList"] Parameters:params successBlock:^(NSDictionary *dic) {
        [WYPublic removeHudToWindow];
        NSArray *array = dic[@"data"][@"locked_list"];
        if ([array count] > 0) {
            LockView *lockVIew = [[LockView alloc]initWithArr:dic[@"data"][@"locked_list"] Count:dic[@"data"][@"locked_total"]];
            [WINDOW addSubview:lockVIew];
        }
        else {
            [WYPublic showMessageWithTitle:@"提示:" Msg:@"信息已过期，请重新刷新页面"];
            [WYPublic removeHudToWindow];
        }
        
    } failedBlock:^{
        [WYPublic showMessageWithTitle:@"提示:" Msg:@"信息已过期，请重新刷新页面"];
        [WYPublic removeHudToWindow];
    } needLog:NO];
}

//加入购物车按钮的监听事件
- (IBAction)addToCarBtnOnClick:(id)sender {
    [ani_layer removeFromSuperlayer];
    ani_layer=[[CALayer alloc]init];
    //购物车显示加一
    WYShopCarModel *model = [[WYShopCarModel alloc]init];
    model.car_id = _currentModel.pdc_id;
    model.car_new_id = _currentModel.pdc_sid; //同一商品ID
    model.imgPath = _currentModel.pdc_img_path;
    model.name = _currentModel.pdc_title;
    model.all_need = _currentModel.pdc_people_indeed;
    model.left_need = _currentModel.pdc_people_left;
    model.qishu   = _currentModel.pdc_qishu;
    
    [[WYDataBase sharedDataBase]insertPdcToCarWithModel:model];
    
    ShoppingCarVC *shopVC = [ShoppingCarVC shareShoppingCarVC];
    shopVC.firstFlag = YES;
    
    [ani_layer removeAllAnimations];
    //加入动画
    [self scaleFirst];
}

/**
 *收藏按钮的动画效果
 ***********************/
//先缩放
- (void)scaleFirst
{
    UIImageView *imageView=[[UIImageView alloc]initWithImage:pdcImg.image];
    imageView.contentMode=UIViewContentModeScaleToFill;
    imageView.frame=CGRectMake(0, 0, pdcImg.frame.size.width, pdcImg.frame.size.height);
    imageView.hidden=YES;
    UIWindow *window = [UIApplication sharedApplication].delegate.window;
    //
    CGPoint point=window.center;
    imageView.center=point;
    ani_layer.contents=imageView.layer.contents;
    //动画起点
    CGPoint cellCenter= [self.tableView convertPoint:self.center toView:window];
    CGPoint startPoint = CGPointMake(cellCenter.x + (pdcImg.center.x - self.frame.size.width/2), cellCenter.y+(pdcImg.center.y - self.frame.size.height/2));
    ani_layer.frame=pdcImg.frame;
    ani_layer.position = startPoint;
    ani_layer.opacity=1;
    
    ani_layer.masksToBounds = YES;
    ani_layer.cornerRadius = ani_layer.bounds.size.width/2;
    [window.layer addSublayer:ani_layer];
    //缩放动画
    CABasicAnimation *scaleAnimation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    scaleAnimation.fromValue = [NSNumber numberWithFloat:1.0];
    scaleAnimation.toValue = [NSNumber numberWithFloat:0.3];
    scaleAnimation.delegate = self;
    scaleAnimation.duration = 0.25f;
    scaleAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    [ani_layer addAnimation:scaleAnimation forKey:@"buy1"];
}
- (void)collectionAnimotion
{
    
    
    
    //动画 终点 都以sel.view为参考系
    CGPoint endpoint= [[WYMainTabBarVC shareMainTaBarVC].customTabBar convertPoint:[[WYMainTabBarVC shareMainTaBarVC] getShoppingCarBtn].center toView:WINDOW];
    UIBezierPath *path=[UIBezierPath bezierPath];
    //动画起点
    CGPoint cellCenter= [self.tableView convertPoint:self.center toView:WINDOW];
    CGPoint startPoint = CGPointMake(cellCenter.x + (pdcImg.center.x - self.frame.size.width/2), cellCenter.y+(pdcImg.center.y - self.frame.size.height/2));
    
    [path moveToPoint:startPoint];
    //贝塞尔曲线中间点
    float sx=startPoint.x;
    float sy=startPoint.y;
    float ex=endpoint.x;
    float ey=endpoint.y;
    float x=sx+(ex-sx)/3;
    float y=sy+(ey-sy)*0.5-400;
    CGPoint centerPoint=CGPointMake(x,y);
    [path addQuadCurveToPoint:endpoint controlPoint:centerPoint];
    
    CAKeyframeAnimation *animation=[CAKeyframeAnimation animationWithKeyPath:@"position"];
    animation.path = path.CGPath;
    animation.removedOnCompletion = NO;
    animation.fillMode = kCAFillModeForwards;
    animation.duration=0.8;
    animation.delegate=self;
    animation.autoreverses= NO;
    animation.timingFunction=[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
    [ani_layer addAnimation:animation forKey:@"buy"];
    //透明度变化
    CABasicAnimation *opacityAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"];
    opacityAnimation.fromValue = [NSNumber numberWithFloat:1.0];
    opacityAnimation.toValue = [NSNumber numberWithFloat:0.8];
    opacityAnimation.duration = 0.8;
    [ani_layer addAnimation:opacityAnimation forKey:@"buy2"];
    
}
- (void)animationDidStop:(CAAnimation *)theAnimation finished:(BOOL)flag {
    //    NSLog(@"---->%@",[theAnimation class]);
    //clearMemory
    if ([theAnimation class] == [CABasicAnimation class]) {
        //关闭隐式动画
        [CATransaction setDisableActions:YES];
        //动画起点
        CGPoint cellCenter= [self.tableView convertPoint:self.center toView:WINDOW];
        CGPoint startPoint = CGPointMake(cellCenter.x + (pdcImg.center.x - self.frame.size.width/2), cellCenter.y+(pdcImg.center.y - self.frame.size.height/2));
        ani_layer.bounds = CGRectMake(0, 0, pdcImg.frame.size.width*0.3, pdcImg.frame.size.height*0.3);
        ani_layer.cornerRadius = ani_layer.bounds.size.width/2;
        ani_layer.position = startPoint;
        [self collectionAnimotion];
        
    }else{
        //结束事件
        [ani_layer removeFromSuperlayer];
        [[WYMainTabBarVC shareMainTaBarVC]updateCountToCar];
    }
    
}

@end
